/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

package org.apache.qpid.client.security.oauth2;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

public class OAuth2SaslClient implements SaslClient
{
    public static final String MECHANISM = "XOAUTH2";
    private final CallbackHandler _callbackHandler;
    private boolean _isComplete = false;

    public OAuth2SaslClient(CallbackHandler callbackHandler)
    {
        _callbackHandler = callbackHandler;
    }

    @Override
    public String getMechanismName()
    {
        return MECHANISM;
    }

    @Override
    public boolean hasInitialResponse()
    {
        return true;
    }

    @Override
    public byte[] evaluateChallenge(byte[] challenge) throws SaslException
    {
        if (_isComplete)
        {
            return new byte[0];
        }

        PasswordCallback callback = new PasswordCallback("promptunused", false);
        Callback[] callbacks = new Callback[] {callback};
        try
        {
            _callbackHandler.handle(callbacks);
        }
        catch (UnsupportedCallbackException e)
        {
            throw new SaslException("Unsupported callback", e);
        }
        catch (IOException e)
        {
            throw new SaslException("Failed to execute callback", e);
        }

        String accessToken = new String(callback.getPassword());
        if (accessToken == null || accessToken.length() == 0)
        {
            throw new SaslException("OAuth2SaslClient requires that the OAuth2 access token is"
                                    + " supplied via the connection's password");
        }
        byte[] response = String.format("auth=Bearer %s\1\1", accessToken).getBytes();
        _isComplete = true;
        return response;
    }

    @Override
    public boolean isComplete()
    {
        return _isComplete;
    }

    @Override
    public Object getNegotiatedProperty(String propName)
    {
        return null;
    }

    @Override
    public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
    {
        throw new SaslException();
    }

    @Override
    public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
    {
        throw new SaslException();
    }

    @Override
    public void dispose() throws SaslException
    {
    }
}
